package com.lagou.sqlSession;

import com.lagou.config.BoundSql;
import com.lagou.config.SqlType;
import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import com.lagou.utils.GenericTokenParser;
import com.lagou.utils.ParameterMapping;
import com.lagou.utils.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

public class SimpleExecutor implements Executor {
    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {

        ResultSet resultSet = (ResultSet)executorSql(configuration, mappedStatement, params);

        String resultType = mappedStatement.getResultType();
        Class<?> resultClass = getClassType(resultType);
        ArrayList<Object> objects = new ArrayList<>();

        // 封装返回结果集
        while (resultSet.next()){
            Object o = resultClass.newInstance();
            // 元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i <= metaData.getColumnCount() ; i++) {
                // 字段名
                String columnName = metaData.getColumnName(i);
                // 字段值
                Object value = resultSet.getObject(columnName);

                // 使用反射或者内省 根据数据库表和实体的对应关系，完成封装
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultClass);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(o, value);
            }
            objects.add(o);
        }

        return (List<E>) objects;
    }

    @Override
    public boolean update(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        int i = (int)executorSql(configuration, mappedStatement, params);
        if(i >= 0){
            return true;
        }
        return false;
    }

    @Override
    public boolean insert(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        int i = (int)executorSql(configuration, mappedStatement, params);
        if(i == 1){
            return true;
        }
        return false;
    }

    @Override
    public boolean delete(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        int i = (int)executorSql(configuration, mappedStatement, params);
        if(i >= 1){
            return true;
        }
        return false;
    }


    private Class<?> getClassType(String param) throws ClassNotFoundException {
        if(param != null){
            Class<?> aClass = Class.forName(param);
            return aClass;
        }
        return null;

    }

    /**
     * 完成对#{id}解析工作，1、将#{}使用？代替 2、解析出对应的数据值
     * @param sql
     * @return
     */
    private BoundSql getBoundSql(String sql) {
        // 标记处理类，配合标记解析器来完成对占位符的解析工作
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();

        GenericTokenParser genericTokenParser = new GenericTokenParser("#{","}",parameterMappingTokenHandler);
        // 解析出来的sql
        String parse = genericTokenParser.parse(sql);
        // 解析出来的参数明名称
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();

        // 将解析后的SQL以及输入参数的集合封装到Boundsql中
        BoundSql boundSql = new BoundSql(parse, parameterMappings);
        return boundSql;
    }


    public Object executorSql(Configuration configuration, MappedStatement mappedStatement, Object... params) throws  Exception{
        // 注册驱动获取连接
        Connection connection = configuration.getDataSource().getConnection();

        // 获取sql语句
        String sql = mappedStatement.getSql();
        // 将sql语句进行格式化
        BoundSql boundSql = getBoundSql(sql);

        // 获取预处理对象
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSql());

        // 获取参数全路径
        String paramType = mappedStatement.getParamType();
        Class<?> paramClass = getClassType(paramType);

        // 设置参数
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        for (int i = 0; i < parameterMappings.size(); i++) {
            ParameterMapping parameterMapping = parameterMappings.get(i);
            String content = parameterMapping.getContent();
            // 使用反射根据参数名称获取实体对象属性值
            Field declaredField = paramClass.getDeclaredField(content);
            declaredField.setAccessible(true);
            Object o = declaredField.get(params[0]);
            preparedStatement.setObject(i+1,o);
        }

        // 通过sql类型判断执行方法
        if(SqlType.SELECT.equals(mappedStatement.getSqlType())){
            return preparedStatement.executeQuery();
        }
        if(SqlType.UPDATE.equals(mappedStatement.getSqlType()) || SqlType.INSERT.equals(mappedStatement.getSqlType()) || SqlType.DELETE.equals(mappedStatement.getSqlType())){
            return preparedStatement.executeUpdate();
        }
        return null;
    }

}
